package com.nunbey.lingxi.activities;

import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.Window;
import android.widget.Button;
import android.widget.Chronometer;

import com.nunbey.lingxi.R;
import com.nunbey.lingxi.lincat.activityinit.BaseActivity;
import com.nunbey.lingxi.lincat.datastore.SharedPreferencesHelper;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

public class LoadActivity extends BaseActivity {
    @Override
    public void onCreate(Bundle savedInstancedState) {
        super.onCreate(savedInstancedState);
        //去掉标题栏
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        //隐藏标题栏：继承AppCompatActivity会失效，且需要在加载页面布局前调用
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.setContentView(R.layout.activity_load);

        if(this.checkSpanTime())
            this.setClock();
        else{
            LoginActivity.startLoginActivity(this);
            this.finish();
        }
    }



    /**
     * @author 李一帆
     * @description 判断当前启动app的时间和上次启动app的时间之差，
     * 若相差时间小于3分钟则直接跳转，如果大于三分钟则播放加载页
     * @return
     */
    private boolean checkSpanTime(){
        SharedPreferencesHelper sharedPreferencesHelper = new SharedPreferencesHelper();

        //获取上一次启动应用的时间
        String lastTimeString = sharedPreferencesHelper.getData(this,"lastOpenTime");
        //写入本次启动应用的时间
        LocalDateTime currentTime = LocalDateTime.now();
        String currentTimeString = currentTime.toString();
        sharedPreferencesHelper.saveData(this,"lastOpenTime",currentTimeString);
        //第一次使用app或清除了缓存
        if(lastTimeString.equals("defaultValue")) return true;
        else{
            LocalDateTime lastTime = LocalDateTime.parse(lastTimeString);
            Long currentInstant = currentTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
            Long lastInstant = lastTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
            Long timeDistance = (currentInstant - lastInstant) / 1000;
            if(timeDistance > 3*60) return true;
            else return false;
        }

    }


    /**
     * @description 加载页定时
     * @author 李一帆
     */
    private void setClock(){
        Chronometer chronometer = this.findViewById(R.id.activity_index_load_clock);
        chronometer.setBase(SystemClock.elapsedRealtime());
        Button button = findViewById(R.id.activity_index_load_timeTip);
        chronometer.setOnChronometerTickListener((chron)->{
            String text = Long.toString(5-((SystemClock.elapsedRealtime() - chron.getBase())/1000));
            button.setText(text);
            if((SystemClock.elapsedRealtime() - chron.getBase()) > (5 * 1000)){
                chronometer.stop();
                LoginActivity.startLoginActivity(this);
                this.finish();
            }
        });
        chronometer.start();

    }


}
